package com.socialnetwork.control;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.socialnetwork.model.UserJB;
import com.socialnetwork.util.UtilString;


public class LoginController implements ActionController{

	public LoginController(){
		
	}

	/**
	 * TASK LOGIN - INIT
	 * 1 - get request uername and password
	 * 2 - Validate username and password is empty
	 * 	2.1 - method loginInvalid return error login
	 * 3 - validate uername and password database
	 * 	3.1 - method loginInvalid return error login
	 * 4 - 
	 * TASK LOGIN - END
	 */
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String username = request.getParameter("username");		
		String password = request.getParameter("password");		
		Connection connection = (Connection) request.getAttribute(UtilString.CONNECTION);
		HttpSession session = (HttpSession) request.getSession();
		String urlRedirect = (String) session.getAttribute(UtilString.URL_REDIRECT);
		
		UserJB user = null;		
		String msgError = "";
		
		if(username != null && password != null){
			if(username.equals("") || password.equals("")){		
				
				msgError = "Username or password empty";
				loginInvalid(msgError);
				response.sendRedirect(UtilString.LOGIN_ERROR_JSP);
				
			}else{
				user = validateLogin(username, password, connection);
				if(user != null){	
					
					System.out.println("LoginController - Add UserJB in session... OK");
					System.out.println("LoginController - " + UtilString.URL_REDIRECT + " = " + urlRedirect);
					session.setAttribute(UtilString.USER_JB, user);
					
					if(urlRedirect == null){
						response.sendRedirect(UtilString.HOME_JSP);	
					}else{
						response.sendRedirect(urlRedirect);
						session.removeAttribute(UtilString.URL_REDIRECT);
					}
					
				}else{
					msgError = "Username or password invalid";
					loginInvalid(msgError);
					response.sendRedirect(UtilString.LOGIN_ERROR_JSP);
				}
				
			}
		}else{
			msgError = "ERROR Login - username and password";
			loginInvalid(msgError);
			response.sendRedirect(UtilString.LOGIN_ERROR_JSP);
		}
	}
	
	private UserJB validateLogin(String username, String password, Connection connection){
		
		//access dao
		
		return new UserJB();
	}
	
	private void loginInvalid(String msgError){
		
		
		//ajax return msg error
	}
	
	
	
}
